<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Backend extends Controller_Template {
	
	public function before()
	{
		if ( ! Request::current()->is_ajax() AND UTF8::substr($this->template, 0, 7) != 'backend')
		{
			$this->template = 'backend';
		}
		
		$logged = FALSE;
		$admin = Kohana::$config->load('backend.admin');
		
		$cookie = array(
			'login' => Cookie::get('backend_login', NULL),
			'hash' => Cookie::get('backend_hash', NULL),
		);
		
		foreach ($admin as $login => $hash)
		{
			if ($cookie['login'] == md5($login) AND $cookie['hash'] == md5($hash))
				$logged = TRUE;
		}
		
		if ( ! $logged 
			AND Request::current()->directory() == 'backend' 
			AND (Request::current()->controller() != 'auth' AND Request::current()->action() != 'login'))
		{
			Request::current()->redirect(URL::site(Route::get('backend')->uri(array(
				'directory' => 'backend',
				'controller' => 'auth',
				'action' => 'login',
			))));
		}
		else
		{
			Cookie::set('backend_login', $cookie['login']);
			Cookie::set('backend_hash', $cookie['hash']);
			
			Model_Reg::set('backend.login', $login);
		}
		
		parent::before();
	}
	
}